package com.example.demo.service;

import com.example.rabbitmq.PaymentReq;
import com.example.rabbitmq.RabbitmqConfig;
import jakarta.annotation.Resource;
import org.apache.catalina.User;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.CompletableFuture;

@Service
public class RabbitmqService {

    @Resource
    private RabbitTemplate rabbitTemplate;
    // 同步
    public String sendMessage(PaymentReq paymentReq) {

        String correlationId = UUID.randomUUID().toString();

        // 设置replyTo和correlationId
        return rabbitTemplate.convertSendAndReceiveAsType(
                RabbitmqConfig.paymentExchange,RabbitmqConfig.paymentRouteKey,
                paymentReq,
                message -> {
                    message.getMessageProperties().setReplyTo("reply.queue");
                    message.getMessageProperties().setCorrelationId(correlationId);
                    return message;
                },
                new ParameterizedTypeReference<String>() {}
        );
    }

    //异步
    public CompletableFuture<String> sendMessage2(PaymentReq paymentReq) {

        String correlationId = UUID.randomUUID().toString();
        // 设置回调函数，
        rabbitTemplate.setConfirmCallback((correlationData, ack, s) -> {
            if (ack){
                System.out.println("ok");
            }else {
                System.out.println("失败"+s);
            }
        });

        // 设置replyTo和correlationId
        return CompletableFuture.supplyAsync(()->{
            return rabbitTemplate.convertSendAndReceiveAsType(
                    RabbitmqConfig.paymentExchange,RabbitmqConfig.paymentRouteKey,
                    paymentReq,
                    message -> {
                        message.getMessageProperties().setReplyTo("reply.queue");
                        message.getMessageProperties().setCorrelationId(correlationId);
                        return message;
                    },
                    new ParameterizedTypeReference<String>() {}
            );
        });
    }

}
